﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace UniverWeb.Services
{
    public class MefControllerFactory : DefaultControllerFactory
    {
        private CompositionContainer _Container;

        public MefControllerFactory(Assembly assembly)
        {
            _Container = new CompositionContainer(new AssemblyCatalog(assembly));
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType != null)
            {
                var controllers = _Container.GetExports<IController>();

                var controllerExport = controllers.Where(item => item.Value.GetType() == controllerType).FirstOrDefault();

                if (controllerExport == null)
                {
                    return base.GetControllerInstance(requestContext, controllerType);
                }

                return controllerExport.Value;
            }
            else
            {
                throw new HttpException((int)HttpStatusCode.NotFound,
                    string.Format(
                        "The controller for path '{0}' could not be found or it does not implement IController.",
                        requestContext.HttpContext.Request.Path
                    )
                );
            }
        }
    }
}